// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化变量
    let selectedMood = '';
    let selectedTags = [];
    let moodChart = null; // 用于存储图表实例
    
    // 获取DOM元素
    const moodButtons = document.querySelectorAll('.mood-btn');
    const tagButtons = document.querySelectorAll('.tag-btn');
    const customTagInput = document.getElementById('custom-tag');
    const moodForm = document.getElementById('mood-form');
    const historyList = document.getElementById('history-list');
    const moodFilter = document.getElementById('mood-filter');
    const generateInsightsBtn = document.getElementById('generate-insights');
    const exportCsvBtn = document.getElementById('export-csv');
    const insightsContent = document.getElementById('insights-content');
    const selectedMoodInput = document.getElementById('selected-mood');
    const selectedTagsInput = document.getElementById('selected-tags');
    const cleanDataBtn = document.getElementById('clean-data'); // 添加清洗数据按钮
    const dailyReportContent = document.getElementById('daily-report-content');
    const generateDailyReportBtn = document.getElementById('generate-daily-report');
    const exportMarkdownBtn = document.getElementById('export-markdown-report');
    
    // 心情按钮点击事件
    moodButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 移除所有按钮的选中状态
            moodButtons.forEach(btn => btn.classList.remove('selected'));
            // 添加当前按钮的选中状态
            this.classList.add('selected');
            // 设置选中的心情
            selectedMood = this.dataset.mood;
            selectedMoodInput.value = selectedMood;
        });
    });
    
    // 标签按钮点击事件
    tagButtons.forEach(button => {
        button.addEventListener('click', function() {
            const tag = this.dataset.tag;
            // 切换选中状态
            this.classList.toggle('selected');
            
            // 更新选中的标签数组
            if (this.classList.contains('selected')) {
                if (!selectedTags.includes(tag)) {
                    selectedTags.push(tag);
                }
            } else {
                selectedTags = selectedTags.filter(t => t !== tag);
            }
            
            selectedTagsInput.value = selectedTags.join(',');
        });
    });
    
    // 自定义标签输入事件
    customTagInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && this.value.trim() !== '') {
            const tag = this.value.trim();
            // 如果标签不在已选标签中，则添加
            if (!selectedTags.includes(tag)) {
                selectedTags.push(tag);
                selectedTagsInput.value = selectedTags.join(',');
            }
            // 清空输入框
            this.value = '';
            e.preventDefault();
        }
    });
    
    // 表单提交事件
    moodForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 获取表单数据
        const description = document.getElementById('mood-description').value;
        
        // 验证必填字段
        if (!selectedMood || !description) {
            alert('请选择心情并填写描述');
            return;
        }
        
        // 创建心情记录对象
        const moodRecord = {
            id: Date.now(), // 简单的ID生成方式
            mood: selectedMood,
            description: description,
            tags: [...selectedTags], // 复制数组以避免引用问题
            date: new Date().toISOString()
        };
        
        // 保存到localStorage
        saveMoodRecord(moodRecord);
        
        // 重置表单
        resetForm();
        
        // 更新历史记录显示
        displayHistory();
        
        // 更新图表
        updateChart();
        
        // 显示成功消息
        alert('心情记录保存成功！');
    });
    
    // 筛选器变化事件
    moodFilter.addEventListener('change', function() {
        displayHistory(this.value);
    });
    
    // 生成洞察按钮点击事件
    generateInsightsBtn.addEventListener('click', function() {
        generateInsights();
    });
    
    // 导出CSV按钮点击事件
    exportCsvBtn.addEventListener('click', function() {
        exportToCSV();
    });
    
    // 数据清洗按钮点击事件
    cleanDataBtn.addEventListener('click', function() {
        importAndCleanCSV();
    });
    
    // 生成每日报告按钮点击事件
    generateDailyReportBtn.addEventListener('click', function() {
        generateDailyReport();
        // 滚动到报告区域
        document.getElementById('daily-report-section').scrollIntoView({ behavior: 'smooth' });
    });
    
    // 导出Markdown报告按钮点击事件
    exportMarkdownBtn.addEventListener('click', function() {
        exportMarkdownReport();
    });
    
    // 保存心情记录到localStorage
    function saveMoodRecord(record) {
        // 获取现有的记录
        let records = JSON.parse(localStorage.getItem('moodRecords')) || [];
        // 添加新记录
        records.push(record);
        // 保存回localStorage
        localStorage.setItem('moodRecords', JSON.stringify(records));
    }
    
    // 获取所有心情记录
    function getMoodRecords() {
        return JSON.parse(localStorage.getItem('moodRecords')) || [];
    }
    
    // 获取今天的记录
    function getTodayRecords() {
        const records = getMoodRecords();
        const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD格式
        
        return records.filter(record => {
            const recordDate = record.date.split('T')[0];
            return recordDate === today;
        });
    }
    
    // 重置表单
    function resetForm() {
        // 重置心情选择
        moodButtons.forEach(btn => btn.classList.remove('selected'));
        selectedMood = '';
        selectedMoodInput.value = '';
        
        // 重置标签选择
        tagButtons.forEach(btn => btn.classList.remove('selected'));
        selectedTags = [];
        selectedTagsInput.value = '';
        
        // 清空描述
        document.getElementById('mood-description').value = '';
        
        // 清空自定义标签输入框
        customTagInput.value = '';
    }
    
    // 显示历史记录
    function displayHistory(filter = 'all') {
        const records = getMoodRecords();
        // 按时间倒序排列
        records.sort((a, b) => new Date(b.date) - new Date(a.date));
        
        // 根据筛选条件过滤
        const filteredRecords = filter === 'all' ? records : records.filter(record => record.mood === filter);
        
        // 清空历史记录列表
        historyList.innerHTML = '';
        
        // 如果没有记录，显示提示信息
        if (filteredRecords.length === 0) {
            historyList.innerHTML = '<p>暂无心情记录</p>';
            return;
        }
        
        // 显示每条记录
        filteredRecords.forEach(record => {
            const recordElement = document.createElement('div');
            recordElement.className = 'history-item';
            
            // 格式化日期
            const date = new Date(record.date);
            const dateString = date.toLocaleDateString('zh-CN');
            const timeString = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
            
            // 心情符号映射
            const moodSymbols = {
                happy: '😊',
                neutral: '😐',
                sad: '😢',
                angry: '😡'
            };
            
            // 创建记录HTML
            recordElement.innerHTML = `
                <div class="history-item-header">
                    <span class="mood-display">${moodSymbols[record.mood] || record.mood}</span>
                    <span class="date-display">${dateString} ${timeString}</span>
                </div>
                <div class="description-display">${escapeHtml(record.description)}</div>
                ${record.tags && record.tags.length > 0 ? 
                    `<div class="tags-display">
                        ${record.tags.map(tag => `<span class="tag-display">${escapeHtml(tag)}</span>`).join('')}
                    </div>` : ''
                }
            `;
            
            historyList.appendChild(recordElement);
        });
    }
    
    // 生成每日报告
    function generateDailyReport() {
        const todayRecords = getTodayRecords();
        
        // 如果没有今天的记录，显示提示
        if (todayRecords.length === 0) {
            dailyReportContent.innerHTML = '<p>暂无今日记录，请先记录今日心情。</p>';
            return;
        }
        
        // 计算平均评分
        const moodScoreMap = {
            happy: 8,
            neutral: 5,
            sad: 3,
            angry: 2
        };
        
        const totalScore = todayRecords.reduce((sum, record) => {
            return sum + (moodScoreMap[record.mood] || 5);
        }, 0);
        
        const averageScore = Math.round((totalScore / todayRecords.length) * 10) / 10;
        
        // 收集所有标签
        const allTags = todayRecords.flatMap(record => record.tags || []);
        
        // 统计标签频率
        const tagCounts = {};
        allTags.forEach(tag => {
            tagCounts[tag] = (tagCounts[tag] || 0) + 1;
        });
        
        // 获取最常见的标签（最多显示5个）
        const topTags = Object.entries(tagCounts)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 5)
            .map(([tag, count]) => tag);
        
        // 生成个性化建议
        const suggestion = generateDailySuggestion(averageScore, topTags);
        
        // 构建报告HTML
        dailyReportContent.innerHTML = `
            <div class="report-item">
                <div class="report-title">📊 平均评分</div>
                <div class="average-score">${averageScore}/10分</div>
            </div>
            
            <div class="report-item">
                <div class="report-title">🏷️ 主要情感标签</div>
                <div class="tag-list">
                    ${topTags.length > 0 ? 
                        topTags.map(tag => `<span class="report-tag">${escapeHtml(tag)}</span>`).join('') : 
                        '<span>暂无标签</span>'}
                </div>
            </div>
            
            <div class="report-item">
                <div class="report-title">💡 今日建议</div>
                <div class="suggestion">${suggestion}</div>
            </div>
        `;
    }
    
    // 生成个性化建议
    function generateDailySuggestion(averageScore, topTags) {
        // 根据评分生成建议
        if (averageScore >= 7.5) {
            return "今天心情很好！继续保持积极的心态，可以和朋友分享这份快乐，或者做一些让自己更加开心的事情。";
        } else if (averageScore >= 5.5) {
            return "今天心情较为平稳，建议尝试一些新鲜事物来增添生活乐趣，比如听音乐、看电影或外出散步。";
        } else if (averageScore >= 3.5) {
            return "今天心情略显平淡，建议多运动或与朋友交流，这有助于提升情绪。";
        } else {
            return "今天心情不太好，不要压抑情绪，可以尝试倾诉、写日记或进行一些放松活动，如冥想或深呼吸。";
        }
    }
    
    // 导出Markdown报告
    function exportMarkdownReport() {
        const todayRecords = getTodayRecords();
        
        // 如果没有今天的记录，显示提示
        if (todayRecords.length === 0) {
            alert('暂无今日记录，无法导出报告。请先记录今日心情。');
            return;
        }
        
        // 计算平均评分
        const moodScoreMap = {
            happy: 8,
            neutral: 5,
            sad: 3,
            angry: 2
        };
        
        const totalScore = todayRecords.reduce((sum, record) => {
            return sum + (moodScoreMap[record.mood] || 5);
        }, 0);
        
        const averageScore = Math.round((totalScore / todayRecords.length) * 10) / 10;
        
        // 收集所有标签
        const allTags = todayRecords.flatMap(record => record.tags || []);
        
        // 统计标签频率
        const tagCounts = {};
        allTags.forEach(tag => {
            tagCounts[tag] = (tagCounts[tag] || 0) + 1;
        });
        
        // 获取最常见的标签（最多显示5个）
        const topTags = Object.entries(tagCounts)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 5)
            .map(([tag, count]) => ({ tag, count }));
        
        // 生成个性化建议
        const suggestion = generateDailySuggestion(averageScore, topTags.map(t => t.tag));
        
        // 获取今天的日期
        const today = new Date();
        const dateString = today.toLocaleDateString('zh-CN');
        const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][today.getDay()];
        
        // 心情符号映射
        const moodSymbols = {
            happy: '😊 开心',
            neutral: '😐 平静',
            sad: '😢 伤心',
            angry: '😡 生气'
        };
        
        // 根据平均分选择emoji表情
        let scoreEmoji = '';
        if (averageScore >= 7.5) {
            scoreEmoji = '😄';
        } else if (averageScore >= 5.5) {
            scoreEmoji = '🙂';
        } else if (averageScore >= 3.5) {
            scoreEmoji = '😐';
        } else {
            scoreEmoji = '😔';
        }
        
        // 生成Markdown内容
        let markdownContent = `# 我的每日心情报告 📔\n\n`;
        markdownContent += `📅 **${dateString}** (${weekday})  ${scoreEmoji}\n\n`;
        
        // 添加个性化标题
        if (averageScore >= 7.5) {
            markdownContent += `🌟 **精彩的一天** - 今天你的心情如阳光般灿烂！\n\n`;
        } else if (averageScore >= 5.5) {
            markdownContent += `🌤️ **平静的一天** - 今天你的心情如湖水般宁静。\n\n`;
        } else if (averageScore >= 3.5) {
            markdownContent += `☁️ **略显平淡的一天** - 今天你的心情有些起伏。\n\n`;
        } else {
            markdownContent += `🌧️ **情绪低落的一天** - 今天你的心情需要一些关怀。\n\n`;
        }
        
        markdownContent += `---\n\n`;
        
        // 心情仪表盘
        markdownContent += `## 🎯 心情仪表盘\n\n`;
        markdownContent += `### 📊 平均心情指数\n`;
        markdownContent += `**${averageScore}**/10 ${scoreEmoji}\n\n`;
        
        // 进度条显示
        const progressBars = Math.round(averageScore);
        markdownContent += `心情饱满度: `;
        for (let i = 1; i <= 10; i++) {
            if (i <= progressBars) {
                markdownContent += '█';
            } else {
                markdownContent += '░';
            }
        }
        markdownContent += ` ${progressBars}/10\n\n`;
        
        // 心情分布
        markdownContent += `### 😊 心情分布图\n\n`;
        const moodCounts = {
            happy: todayRecords.filter(r => r.mood === 'happy').length,
            neutral: todayRecords.filter(r => r.mood === 'neutral').length,
            sad: todayRecords.filter(r => r.mood === 'sad').length,
            angry: todayRecords.filter(r => r.mood === 'angry').length
        };
        
        // 找出主导心情
        let dominantMood = '';
        let maxCount = 0;
        for (const [mood, count] of Object.entries(moodCounts)) {
            if (count > maxCount) {
                maxCount = count;
                dominantMood = mood;
            }
        }
        
        if (dominantMood) {
            markdownContent += `今天的主导心情是: **${moodSymbols[dominantMood]}**\n\n`;
        }
        
        for (const [mood, count] of Object.entries(moodCounts)) {
            if (count > 0) {
                const percentage = Math.round((count / todayRecords.length) * 100);
                markdownContent += `- ${moodSymbols[mood]}: ${count}次 (${percentage}%)\n`;
                
                // 添加进度条
                const barLength = Math.round(percentage / 10);
                markdownContent += `  [`;
                for (let i = 0; i < 10; i++) {
                    if (i < barLength) {
                        markdownContent += '●';
                    } else {
                        markdownContent += '○';
                    }
                }
                markdownContent += `] ${percentage}%\n`;
            }
        }
        markdownContent += `\n`;
        
        // 主要情感标签
        if (topTags.length > 0) {
            markdownContent += `## 🏷️ 情感标签云\n\n`;
            markdownContent += `今天你的情感关键词是:\n\n`;
            
            topTags.forEach(({ tag, count }, index) => {
                // 根据频率调整标签大小
                let fontSize = '';
                if (index === 0) {
                    fontSize = '####';
                } else if (index === 1) {
                    fontSize = '###';
                } else if (index === 2) {
                    fontSize = '##';
                } else {
                    fontSize = '#';
                }
                markdownContent += `${fontSize} **${tag}** `;
            });
            markdownContent += `\n\n`;
            
            markdownContent += `详细统计:\n`;
            topTags.forEach(({ tag, count }) => {
                markdownContent += `- **${tag}**: ${count}次\n`;
            });
            markdownContent += `\n`;
        }
        
        // 今日建议
        markdownContent += `## 💡 心灵小贴士\n\n`;
        markdownContent += `> ${suggestion}\n\n`;
        
        // 详细记录
        markdownContent += `## 📝 心情日记\n\n`;
        todayRecords.forEach((record, index) => {
            const recordTime = new Date(record.date).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
            markdownContent += `### 🕐 ${recordTime} | ${moodSymbols[record.mood]}\n\n`;
            
            // 添加引用格式的描述
            markdownContent += `💬 **心情独白**:\n`;
            markdownContent += `> ${record.description}\n\n`;
            
            if (record.tags && record.tags.length > 0) {
                markdownContent += `🏷️ **相关标签**: `;
                record.tags.forEach(tag => {
                    markdownContent += `\`#${tag}\` `;
                });
                markdownContent += `\n\n`;
            }
            
            // 添加分隔线（除了最后一条记录）
            if (index < todayRecords.length - 1) {
                markdownContent += `---\n\n`;
            }
        });
        
        // 心情趋势分析
        markdownContent += `## 📈 心情趋势分析\n\n`;
        markdownContent += `回顾过去一周你的心情变化:\n\n`;
        
        // 生成图表数据
        const chartData = getLast7DaysData();
        markdownContent += `| 日期 | 心情评分 | 情绪状态 |\n`;
        markdownContent += `|------|----------|----------|\n`;
        
        chartData.dates.forEach((date, index) => {
            const score = chartData.moodScores[index];
            const displayScore = score !== null ? score : '无数据';
            
            // 根据评分确定情绪状态
            let status = '';
            if (score === null) {
                status = '未记录';
            } else if (score >= 7.5) {
                status = '很好 🌟';
            } else if (score >= 5.5) {
                status = '良好 😊';
            } else if (score >= 3.5) {
                status = '一般 🌤️';
            } else {
                status = '较差 🌧️';
            }
            
            const dateObj = new Date(date);
            const dateStr = `${dateObj.getMonth() + 1}/${dateObj.getDate()}`;
            markdownContent += `| ${dateStr} | ${displayScore} | ${status} |\n`;
        });
        
        markdownContent += `\n`;
        
        // 添加总结和鼓励
        markdownContent += `## 🌈 总结与展望\n\n`;
        markdownContent += `感谢你今天的记录！📝\n\n`;
        markdownContent += `持续记录心情有助于你更好地了解自己的情绪模式。`;
        markdownContent += `无论是喜悦还是忧伤，每一种情绪都有它存在的意义。`;
        markdownContent += `愿你每天都能在记录中找到内心的平静与力量。\n\n`;
        markdownContent += `继续加油！明天又是崭新的一天！☀️\n\n`;
        
        // 添加项目信息
        markdownContent += `---\n\n`;
        markdownContent += `❤️ 由[每日心情采集器](https://github.com)生成\n\n`;
        
        // 创建并下载文件
        const filename = `心情报告_${today.getFullYear()}年${String(today.getMonth() + 1).padStart(2, '0')}月${String(today.getDate()).padStart(2, '0')}日.md`;
        
        const blob = new Blob([markdownContent], { type: 'text/markdown;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
    
    // 生成洞察报告
    function generateInsights() {
        const records = getMoodRecords();
        
        // 如果没有足够的数据，显示提示
        if (records.length === 0) {
            insightsContent.innerHTML = '<p>暂无数据，无法生成洞察报告。请先记录一些心情。</p>';
            return;
        }
        
        // 显示加载状态
        insightsContent.innerHTML = '<div class="loading">正在分析你的心情数据...</div>';
        
        // 模拟AI分析过程（实际项目中这里会调用通义灵码API）
        setTimeout(() => {
            // 生成模拟的洞察报告
            const report = generateMockInsights(records);
            
            // 显示洞察报告
            insightsContent.innerHTML = `
                <div class="insight-report">
                    <h3>情绪洞察报告</h3>
                    <div class="insight-section">
                        <h4>📊 情绪模式识别</h4>
                        <p>${report.patterns}</p>
                    </div>
                    <div class="insight-section">
                        <h4>🔍 情绪触发因素分析</h4>
                        <p>${report.triggers}</p>
                    </div>
                    <div class="insight-section">
                        <h4>💡 关键发现总结</h4>
                        <p>${report.findings}</p>
                    </div>
                    <div class="insight-section">
                        <h4>🌟 个性化建议</h4>
                        <p>${report.suggestions}</p>
                    </div>
                    <p style="margin-top: 1rem; font-size: 0.9rem; color: #7f8c8d;">
                        基于你记录的${records.length}条心情数据生成
                    </p>
                </div>
            `;
        }, 1500);
    }
    
    // 生成模拟的洞察报告
    function generateMockInsights(records) {
        // 这里是一个模拟函数，实际项目中应该调用通义灵码API
        // 根据记录数据生成一些通用的洞察
        
        // 统计心情分布
        const moodCount = {
            happy: records.filter(r => r.mood === 'happy').length,
            neutral: records.filter(r => r.mood === 'neutral').length,
            sad: records.filter(r => r.mood === 'sad').length,
            angry: records.filter(r => r.mood === 'angry').length
        };
        
        // 计算情绪分布百分比
        const totalRecords = records.length;
        const moodPercentage = {};
        for (const mood in moodCount) {
            moodPercentage[mood] = totalRecords > 0 ? Math.round((moodCount[mood] / totalRecords) * 100) : 0;
        }
        
        // 找出最常见和最少见的心情
        let mostCommonMood = '';
        let leastCommonMood = '';
        let maxCount = 0;
        let minCount = totalRecords;
        
        for (const [mood, count] of Object.entries(moodCount)) {
            if (count > maxCount) {
                maxCount = count;
                mostCommonMood = mood;
            }
            if (count < minCount) {
                minCount = count;
                leastCommonMood = mood;
            }
        }
        
        // 心情描述映射
        const moodDescriptions = {
            happy: '开心',
            neutral: '平静',
            sad: '伤心',
            angry: '生气'
        };
        
        // 心情符号映射
        const moodSymbols = {
            happy: '😊',
            neutral: '😐',
            sad: '😢',
            angry: '😡'
        };
        
        // 分析标签
        const allTags = records.flatMap(r => r.tags || []);
        const tagCounts = {};
        allTags.forEach(tag => {
            tagCounts[tag] = (tagCounts[tag] || 0) + 1;
        });
        
        // 找出最常见的标签
        const sortedTags = Object.entries(tagCounts)
            .sort((a, b) => b[1] - a[1]);
            
        const mostCommonTags = sortedTags
            .slice(0, 3)
            .map(([tag, count]) => `${tag}(${count}次)`);
            
        const leastCommonTags = sortedTags
            .slice(-3)
            .reverse()
            .map(([tag, count]) => `${tag}(${count}次)`);
        
        // 按工作日和周末分析情绪模式
        const weekdayRecords = records.filter(r => {
            const date = new Date(r.date);
            const day = date.getDay();
            return day !== 0 && day !== 6; // 非周末
        });
        
        const weekendRecords = records.filter(r => {
            const date = new Date(r.date);
            const day = date.getDay();
            return day === 0 || day === 6; // 周末
        });
        
        const weekdayHappyCount = weekdayRecords.filter(r => r.mood === 'happy').length;
        const weekendHappyCount = weekendRecords.filter(r => r.mood === 'happy').length;
        
        // 计算工作日和周末的开心比例
        const weekdayHappyRatio = weekdayRecords.length > 0 ? 
            Math.round((weekdayHappyCount / weekdayRecords.length) * 100) : 0;
        const weekendHappyRatio = weekendRecords.length > 0 ? 
            Math.round((weekendHappyCount / weekendRecords.length) * 100) : 0;
            
        // 细化标签分类
        const detailedTags = {
            '工作任务': ['工作', '项目', '任务', 'deadline', '加班'],
            '同事关系': ['同事', '上司', '团队', '合作'],
            '家庭生活': ['家人', '父母', '孩子', '家庭'],
            '朋友社交': ['朋友', '聚会', '社交'],
            '健康状况': ['健康', '生病', '锻炼', '运动'],
            '学习成长': ['学习', '读书', '技能', '进步']
        };
        
        const tagCategories = {};
        Object.keys(detailedTags).forEach(category => {
            tagCategories[category] = 0;
            detailedTags[category].forEach(keyword => {
                if (tagCounts[keyword]) {
                    tagCategories[category] += tagCounts[keyword];
                }
            });
        });
        
        // 找出影响最大的标签分类
        const sortedCategories = Object.entries(tagCategories)
            .filter(([category, count]) => count > 0)
            .sort((a, b) => b[1] - a[1]);
            
        const mostInfluentialCategories = sortedCategories
            .slice(0, 3)
            .map(([category, count]) => `${category}(${count}次)`);
            
        const leastInfluentialCategories = sortedCategories
            .slice(-3)
            .reverse()
            .map(([category, count]) => `${category}(${count}次)`);
            
        // 分析情绪趋势（最近7天）
        const oneWeekAgo = new Date();
        oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
        
        const recentRecords = records.filter(r => new Date(r.date) >= oneWeekAgo);
        const recentMoodCount = {
            happy: recentRecords.filter(r => r.mood === 'happy').length,
            neutral: recentRecords.filter(r => r.mood === 'neutral').length,
            sad: recentRecords.filter(r => r.mood === 'sad').length,
            angry: recentRecords.filter(r => r.mood === 'angry').length
        };
        
        // 计算最近一周的情绪分布
        const recentTotal = recentRecords.length;
        const recentMoodPercentage = {};
        for (const mood in recentMoodCount) {
            recentMoodPercentage[mood] = recentTotal > 0 ? Math.round((recentMoodCount[mood] / recentTotal) * 100) : 0;
        }
        
        // 按月份分析情绪（如果数据足够）
        const monthlyData = {};
        records.forEach(record => {
            const date = new Date(record.date);
            const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
            if (!monthlyData[monthKey]) {
                monthlyData[monthKey] = {
                    happy: 0,
                    neutral: 0,
                    sad: 0,
                    angry: 0,
                    total: 0
                };
            }
            monthlyData[monthKey][record.mood]++;
            monthlyData[monthKey].total++;
        });
        
        // 找出情绪最好的月份和最差的月份
        let bestMonth = '';
        let worstMonth = '';
        let bestMonthHappyRatio = 0;
        let worstMonthHappyRatio = 100;
        
        for (const month in monthlyData) {
            const data = monthlyData[month];
            const happyRatio = data.total > 0 ? (data.happy / data.total) * 100 : 0;
            if (happyRatio > bestMonthHappyRatio) {
                bestMonthHappyRatio = happyRatio;
                bestMonth = month;
            }
            if (happyRatio < worstMonthHappyRatio) {
                worstMonthHappyRatio = happyRatio;
                worstMonth = month;
            }
        }
        
        // 分析描述文本长度（了解用户表达习惯）
        const descriptionLengths = records.map(r => r.description.length);
        const avgDescriptionLength = descriptionLengths.reduce((a, b) => a + b, 0) / descriptionLengths.length;
        const avgDescriptionWords = Math.round(avgDescriptionLength / 3); // 中文平均字数
        
        // 生成更丰富的报告
        return {
            patterns: `在你记录的${totalRecords}条心情中，${moodSymbols[mostCommonMood]}${moodDescriptions[mostCommonMood]}情绪出现频率最高，占${moodPercentage[mostCommonMood]}%。而${moodSymbols[leastCommonMood]}${moodDescriptions[leastCommonMood]}情绪相对较少，仅占${moodPercentage[leastCommonMood]}%。${
                weekdayHappyRatio > weekendHappyRatio 
                ? `你在工作日的开心情绪比例为${weekdayHappyRatio}%，而周末为${weekendHappyRatio}%，说明你在工作或学习中获得了较多满足感。` 
                : `你在周末的开心情绪比例为${weekendHappyRatio}%，而工作日为${weekdayHappyRatio}%，说明你很好地利用了休息时间来放松和享受生活。`
            }${recentRecords.length > 0 ? `最近一周内，你的情绪状态呈现出${recentMoodPercentage.happy > recentMoodPercentage.sad + recentMoodPercentage.angry ? '较为积极' : '一定波动'}的趋势。` : ''}${bestMonth ? `历史数据显示，${bestMonth}月是你情绪最好的月份，而${worstMonth}月相对较差。` : ''}`,
            
            triggers: `根据你的描述，常见标签包括：${mostCommonTags.length > 0 ? mostCommonTags.join('、') : '暂无标签数据'}，而较少提及的标签有：${leastCommonTags.length > 0 ? leastCommonTags.join('、') : '暂无数据'}。进一步分析发现，影响你情绪的主要因素集中在：${mostInfluentialCategories.length > 0 ? mostInfluentialCategories.join('、') : '暂无明显因素'}等类别，而${leastInfluentialCategories.length > 0 ? leastInfluentialCategories.join('、') : '其他因素'}对你的影响相对较小。${mostInfluentialCategories.length > 0 ? '这些因素对情绪影响较大，建议你可以针对性地进行调整和优化。' : ''}`,
            
            findings: `你是一个善于自我反思的人，能够清晰地表达自己的情绪和感受。在所有记录中，${moodSymbols[mostCommonMood]}${moodDescriptions[mostCommonMood]}情绪占主导地位，占总记录的${Math.round((maxCount / totalRecords) * 100)}%。你的平均每次记录包含约${avgDescriptionWords}个词，说明你对情绪的描述较为${
                avgDescriptionWords > 20 ? '详细' : 
                avgDescriptionWords > 10 ? '适中' : '简洁'
            }。这种自我觉察能力是情绪管理的重要基础，有助于提升你的心理韧性和情绪调节能力。`,
            
            suggestions: `${mostCommonMood === 'happy' ? '继续保持这种积极的状态，同时可以尝试记录更多积极情绪的触发因素，以便在情绪低落时参考。' : ''}${mostCommonMood === 'sad' || mostCommonMood === 'angry' ? '建议你在情绪低落时尝试进行一些放松活动，如散步、听音乐或冥想。' : ''}${mostCommonMood === 'neutral' ? '你的情绪整体较为平稳，可以尝试一些新鲜事物来增添生活乐趣，比如学习新技能或结识新朋友。' : ''}同时，可以尝试正念练习、写日记或与信任的人交流，这些方法都有助于增强你的情绪调节能力。建议你${
                totalRecords < 20 ? '继续记录更多数据，以便获得更准确的分析结果。' :
                totalRecords < 50 ? '保持当前的记录频率，同时可以尝试更详细地描述情绪触发的情境。' :
                '继续保持良好的记录习惯，丰富的数据将为你提供更深入的洞察。'
            }`
        };
    }
    
    // 转义HTML特殊字符，防止XSS攻击
    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    // 将心情数据导出为CSV格式
    function exportToCSV() {
        const records = getMoodRecords();
        
        if (records.length === 0) {
            alert('没有数据可以导出');
            return;
        }
        
        // 创建CSV内容
        let csvContent = '\uFEFF'; // 添加BOM以支持中文
        csvContent += 'ID,日期,时间,心情,描述,标签\n'; // CSV标题行
        
        // 添加数据行
        records.forEach(record => {
            const date = new Date(record.date);
            const dateString = date.toLocaleDateString('zh-CN');
            const timeString = date.toLocaleTimeString('zh-CN');
            
            // 心情符号映射
            const moodMap = {
                happy: '开心',
                neutral: '平静',
                sad: '伤心',
                angry: '生气'
            };
            
            // 转义CSV特殊字符
            const escapeCSV = (text) => {
                if (typeof text !== 'string') return text;
                if (text.includes(',') || text.includes('"') || text.includes('\n')) {
                    return `"${text.replace(/"/g, '""')}"`;
                }
                return text;
            };
            
            const tags = record.tags ? record.tags.join(';') : '';
            
            csvContent += `${record.id},${dateString},${timeString},${moodMap[record.mood] || record.mood},${escapeCSV(record.description)},${escapeCSV(tags)}\n`;
        });
        
        // 创建并下载文件
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const filename = `mood_data_${year}${month}${day}.csv`;
        
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    // 清洗CSV数据：删除空值和重复记录
    function cleanCSVData(records) {
        // 深拷贝记录以避免修改原始数据
        let cleanedRecords = JSON.parse(JSON.stringify(records));
        
        // 1. 删除空值记录
        cleanedRecords = cleanedRecords.filter(record => {
            // 检查必要字段是否为空
            return record.id && 
                   record.date && 
                   record.mood && 
                   record.description && 
                   record.description.trim() !== '';
        });
        
        // 2. 删除重复记录（基于ID、日期、心情、描述）
        const uniqueRecords = [];
        const seenRecords = new Set();
        
        cleanedRecords.forEach(record => {
            // 创建一个唯一的标识符，用于检测重复
            const recordKey = `${record.id}|${record.date}|${record.mood}|${record.description}`;
            
            if (!seenRecords.has(recordKey)) {
                seenRecords.add(recordKey);
                uniqueRecords.push(record);
            }
        });
        
        return uniqueRecords;
    }

    // 从CSV导入并清洗数据
    function importAndCleanCSV() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.csv';
        
        input.onchange = e => {
            const file = e.target.files[0];
            const reader = new FileReader();
            
            reader.onload = function(event) {
                const csvData = event.target.result;
                const cleanedData = cleanCSVData(parseCSV(csvData));
                
                // 显示清洗结果
                alert(`数据清洗完成！\n原始记录数: ${parseCSV(csvData).length}\n清洗后记录数: ${cleanedData.length}\n删除了 ${parseCSV(csvData).length - cleanedData.length} 条无效或重复记录`);
                
                // 可选：将清洗后的数据保存回localStorage
                if (confirm('是否将清洗后的数据保存到本地存储中？')) {
                    localStorage.setItem('moodRecords', JSON.stringify(cleanedData));
                    displayHistory();
                    updateChart(); // 更新图表
                    alert('数据已保存！');
                }
            };
            
            reader.readAsText(file, 'utf-8');
        };
        
        input.click();
    }

    // 简单的CSV解析函数
    function parseCSV(csvText) {
        const lines = csvText.split('\n').filter(line => line.trim() !== '');
        const records = [];
        
        if (lines.length <= 1) return records; // 只有标题或空文件
        
        // 跳过标题行
        for (let i = 1; i < lines.length; i++) {
            const line = lines[i].trim();
            if (!line) continue;
            
            // 简单的CSV行解析（不处理引号中的逗号）
            const fields = line.split(',');
            
            // 心情中文到英文的映射
            const moodMapReverse = {
                '开心': 'happy',
                '平静': 'neutral',
                '伤心': 'sad',
                '生气': 'angry'
            };
            
            // 解析标签（如果存在）
            const tags = fields[5] ? fields[5].split(';') : [];
            
            records.push({
                id: fields[0],
                date: fields[1] + ' ' + fields[2], // 简化的日期处理
                mood: moodMapReverse[fields[3]] || fields[3],
                description: fields[4],
                tags: tags
            });
        }
        
        return records;
    }
    
    // 获取最近一周的数据
    function getLast7DaysData() {
        const records = getMoodRecords();
        const today = new Date();
        const sevenDaysAgo = new Date(today);
        sevenDaysAgo.setDate(today.getDate() - 6); // 包括今天，共7天数据
        
        // 创建最近7天的日期数组
        const dates = [];
        for (let i = 6; i >= 0; i--) {
            const date = new Date(today);
            date.setDate(today.getDate() - i);
            dates.push(date.toISOString().split('T')[0]); // YYYY-MM-DD格式
        }
        
        // 按日期分组记录
        const recordsByDate = {};
        records.forEach(record => {
            const date = record.date.split('T')[0]; // 提取日期部分
            if (!recordsByDate[date]) {
                recordsByDate[date] = [];
            }
            recordsByDate[date].push(record);
        });
        
        // 为每一天计算平均心情评分
        const moodScores = dates.map(date => {
            const recordsForDate = recordsByDate[date] || [];
            if (recordsForDate.length === 0) {
                return null; // 没有记录则返回null
            }
            
            // 心情到评分的映射 (1-10分)
            const moodScoreMap = {
                happy: 8,
                neutral: 5,
                sad: 3,
                angry: 2
            };
            
            // 计算平均分
            const totalScore = recordsForDate.reduce((sum, record) => {
                return sum + (moodScoreMap[record.mood] || 5); // 默认5分
            }, 0);
            
            return Math.round(totalScore / recordsForDate.length * 10) / 10; // 保留一位小数
        });
        
        return { dates, moodScores };
    }
    
    // 更新图表
    function updateChart() {
        // 检查Chart.js是否已加载
        if (typeof Chart === 'undefined') {
            console.warn('Chart.js 未加载，跳过图表渲染');
            return;
        }
        
        const chartData = getLast7DaysData();
        const canvas = document.getElementById('moodChart');
        
        // 确保canvas元素存在
        if (!canvas) {
            console.warn('未找到 moodChart 元素，跳过图表渲染');
            return;
        }
        
        const ctx = canvas.getContext('2d');
        
        // 如果图表已存在，先销毁它
        if (moodChart) {
            moodChart.destroy();
        }
        
        // 创建新图表
        moodChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: chartData.dates.map(date => {
                    const d = new Date(date);
                    return `${d.getMonth() + 1}/${d.getDate()}`;
                }),
                datasets: [{
                    label: '心情评分',
                    data: chartData.moodScores,
                    borderColor: 'rgb(54, 162, 235)',
                    backgroundColor: 'rgba(54, 162, 235, 0.1)',
                    borderWidth: 3,
                    pointRadius: 5,
                    pointBackgroundColor: 'rgb(54, 162, 235)',
                    fill: true,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        min: 0,
                        max: 10,
                        ticks: {
                            stepSize: 2
                        },
                        title: {
                            display: true,
                            text: '心情评分 (1-10分)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '日期'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `评分: ${context.parsed.y}`;
                            }
                        }
                    }
                }
            }
        });
    }

    // 等待Chart.js加载完成后再初始化图表
    function initChart() {
        if (typeof Chart !== 'undefined') {
            updateChart();
        } else {
            // 如果Chart.js还未加载完成，等待一段时间后重试
            setTimeout(initChart, 100);
        }
    }

    // 初始化历史记录显示和图表
    try {
        displayHistory();
        // 初始化图表
        initChart();
        // 生成初始每日报告
        generateDailyReport();
    } catch (error) {
        console.error('初始化时出错:', error);
    }
});